package com.by.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.by.auto.TokenProperties;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * date 2025/2/10 14:01
 * author bjj
 * decoration
 * version 1.0
 * since jdk11
 */
public class TokenTemplate {
    TokenProperties tokenProperties;

    public TokenTemplate(TokenProperties tokenProperties) {
        this.tokenProperties = tokenProperties;
    }

    /**
     * 生成token
     *
     * @param payload
     * @return
     */
    public String generateToken(Map payload) {
        String token = JWT.create().withHeader(getHeader())
                .withPayload(payload)
                .withIssuer("by")
                .withExpiresAt(getExpireDate())
                .sign(Algorithm.HMAC256(tokenProperties.getSecret()));
        return token;
    }

    public ValidResult valid(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(tokenProperties.getSecret())).build();
        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        } catch (JWTDecodeException e) {
           return new ValidResult(1, "token无效", null);
        }catch (TokenExpiredException e){
            return new ValidResult(2, "token已过期", null);
        }
        Map<String, Claim> payload = jwt.getClaims();
        Map<String,Object> map = new HashMap<>();
        map.put("id",payload.get("id").asInt());
        map.put("username",payload.get("username").asString());
        return new ValidResult(3, "验证成功", map);

    }

    Date getExpireDate() {
        return new Date(System.currentTimeMillis() + tokenProperties.getValidTime());
    }

    Map getHeader() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "JWT");
        map.put("alg", "HMAC256");
        return map;
    }

}
